import { ExtensionContext, commands, window, workspace, QuickPickItem, QuickPickOptions } from 'vscode'
import { IWordResult, EnginesEnum } from './types'
import translatePlatforms from './translate'

import { camelCase, paramCase, pascalCase, snakeCase, constantCase, capitalCase, dotCase, headerCase, noCase, pathCase } from 'change-case'

function checkupdate(context: ExtensionContext) {
  const { packageJSON } = context.extension // 获取packjson配置
  const { globalState } = context // 获取全局状态
  const key = `${packageJSON.name}-${packageJSON.version}`
  const currentVersion = packageJSON.version
  const oldVersion = globalState.get(key)
  const contentText = ` ${packageJSON.displayName}更新`
  if (currentVersion !== oldVersion) {
    globalState.update(key, currentVersion)
    window.showInformationMessage(contentText, { modal: true })
  }
}

export function activate(context: ExtensionContext) {
  checkupdate(context) // 检查当前版本是否需要更新
  const translation = commands.registerCommand('extension.translation', main)
  context.subscriptions.push(translation)
}

function isEnglish(word: string): boolean {
  return /^[a-zA-Z\d\s\/\-\._]+$/.test(word)
}

const translateCacheWords: IWordResult[] = []

async function getTranslateResult(text: string) {
  const engine: EnginesEnum = workspace.getConfiguration('zflTranslation').translationEngine
  const cache = translateCacheWords.find((item) => item.engine == engine && item.text == text)
  if (cache) {
    return cache.result
  }
  // 根据设置获取对应翻译函数
  const translate = translatePlatforms[engine]
  // 判断当前选中的文字是英文还是中文
  const language = isEnglish(text) ? 'zh' : 'en'
  try {
    window.showQuickPick([{ label: '网络翻译中...' }])
    const result = await translate(text, language)
    if (result) {
      translateCacheWords.push({ engine, text, result })
    }
    return result
  } catch (error) {
    window.showInformationMessage(`${engine}翻译异常,请检查网络或密钥配置是否正确 ${JSON.stringify(error)}`)
    return null
  }
}

const changeCaseMap = [
  { name: 'camelCase', handle: camelCase, description: 'camelCase 驼峰(小)' },
  { name: 'pascalCase', handle: pascalCase, description: 'pascalCase 驼峰(大)' },
  { name: 'snakeCase', handle: snakeCase, description: 'snakeCase 下划线' },
  { name: 'paramCase', handle: paramCase, description: 'paramCase 中划线(小)' },
  { name: 'headerCase', handle: headerCase, description: 'headerCase 中划线(大)' },
  { name: 'noCase', handle: noCase, description: 'noCase 分词(小)' },
  { name: 'capitalCase', handle: capitalCase, description: 'capitalCase 分词(大)' },
  { name: 'dotCase', handle: dotCase, description: 'dotCase 对象属性' },
  { name: 'pathCase', handle: pathCase, description: 'pathCase 文件路径' },
  { name: 'constantCase', handle: constantCase, description: 'constantCase 常量' },
]
async function vscodeSelect(word: string): Promise<string | undefined> {
  const isEnglishWord = isEnglish(word)
  const items: QuickPickItem[] = isEnglishWord ? changeCaseMap.map((item) => ({ label: item.handle(word) })) : [{ label: word }]
  const opts: QuickPickOptions = {
    matchOnDescription: false,
    placeHolder: 'choose replace 选择替换',
  }
  const selections = await window.showQuickPick(items, opts)
  if (!selections) {
    return
  }
  return selections.label
}

async function main() {
  // 获取编辑器
  const editor = window.activeTextEditor
  if (!editor) {
    return
  }
  // 获取选中文字
  const selection = editor.selection
  const selectd = editor.document.getText(selection)

  // 拿到翻译后的结果
  const translated = await getTranslateResult(selectd)
  if (!translated) return
  // 拿到格式转换后的结果
  const userSelectd = await vscodeSelect(translated)
  if (!userSelectd) return
  // 替换文案
  editor.edit((buider) => buider.replace(selection, userSelectd))
}

export function deactivate() {}
